//
//  DoorLockViewController.m
//  RONGAO
//
//  Created by Kendama on 2018/2/26.
//  Copyright © 2018年 wei wang. All rights reserved.
//

#import "DoorLockViewController.h"
#import "DoorLockSettingViewController.h"
#import "UnlockingHistoryTableViewCell.h"
#import "GetUnlockingListApi.h"
#import "GetAlertListApi.h"

@interface DoorLockViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong)UIView *headView;
@property(nonatomic,strong)UIButton *doorButton;
@property(nonatomic,strong)UISegmentedControl *segmentedControl;
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *dataSource;
@property(nonatomic,assign)int page;
@property(nonatomic,assign)NSInteger type;
//@property(nonatomic,strong)UIAlertController *alert;
//@property(nonatomic,strong)UIAlertController *input;

@end

@implementation DoorLockViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.page = 1;
    self.type = 0;
    [self.tableView.mj_header beginRefreshing];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(unlockStatues:) name:AddFingerprintOrCardStateNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(OpenLock:) name:@"OpenLock" object:nil];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"OpenLock" object:nil];
}


#pragma mark - --------------------------点击事件--------------------------
- (void)OpenLock:(NSNotification *)notice {
    
    [[AlertViewManager shareManager].alertController dismissViewControllerAnimated:YES completion:nil];
    
    __weak typeof(self) weak = self;
    [[AlertViewManager shareManager] initWithTitle:@"提示" message:notice.object cancleButtonTitle:@"取消" OtherButtonsArray:@[@"确定"] clickAtIndex:^(NSInteger buttonIndex, UIAlertController *alertController) {
        if(buttonIndex == 1) {
            [[AlertViewManager shareManager] initWithEditActionTitle:@"开锁密码" message:@"请输入门锁密码" cancleButtonTitle:@"取消" OtherButtonsArray:@[@"确定"] clickAtIndex:^(NSInteger buttonIndex, UIAlertController *alertController) {
                if( buttonIndex == 1 ) {
                    UITextField *passwordField = alertController.textFields[0];
                    [[WiFiSendDataManager defaultService] remoteUnlocking:weak.deviceMac value:passwordField.text];
                } else {
                    weak.doorButton.selected = NO;
                }
            }];
        } else {
            weak.doorButton.selected = NO;
        }
    }];
}

- (void)onRightButtonClick:(id)sender
{
    DoorLockSettingViewController *vc = [DoorLockSettingViewController new];
    vc.deviceMac = _deviceMac;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)didClickDoorButton
{
    __weak typeof(self) weak = self;
    self.doorButton.selected = !self.doorButton.selected;
    [[AlertViewManager shareManager] initWithTitle:@"提示" message:@"请在锁端按8#" cancleButtonTitle:@"取消" OtherButtonsArray:@[@"确定"] clickAtIndex:^(NSInteger buttonIndex, UIAlertController *alertController) {
        if(buttonIndex == 1) {
            [[AlertViewManager shareManager] initWithEditActionTitle:@"开锁密码" message:@"请输入门锁密码" cancleButtonTitle:@"取消" OtherButtonsArray:@[@"确定"] clickAtIndex:^(NSInteger buttonIndex, UIAlertController *alertController) {
                if( buttonIndex == 1 ) {
                    UITextField *passwordField = alertController.textFields[0];
                    [[WiFiSendDataManager defaultService] remoteUnlocking:weak.deviceMac value:passwordField.text];
                } else {
                    weak.doorButton.selected = NO;
                }
            }];
        } else {
            weak.doorButton.selected = NO;
        }
    }];
}

- (void)unlockStatues:(NSNotification *)no {
    int state = (int)strtoul([no.object UTF8String], 0, 16);
    
    self.doorButton.selected = (state == 1);
}

-(void)didClicksegmentedControlAction:(UISegmentedControl *)Seg
{
    self.type = Seg.selectedSegmentIndex;
    self.page = 1;
    [self updateDataSource];
}

#pragma mark - --------------------------事件处理--------------------------
- (void)updateDataSource
{
    __weak typeof(self) weak = self;

    if (self.type == 0)
    {
        [GetUnlockingListApi getOpenListWithDeviceMac:self.deviceMac page:self.page success:^(NSArray<UnlockingModel *> *list) {
            [weak.tableView.mj_footer endRefreshing];
            [weak.tableView.mj_header endRefreshing];
            if (weak.page == 1)
            {
                [weak.dataSource removeAllObjects];
                [weak.dataSource addObjectsFromArray:list];
                [weak.tableView reloadData];
            }
            else
            {
                if (list.count != 0)
                {
                    [weak.dataSource addObjectsFromArray:list];
                    [weak.tableView reloadData];
                }
                else
                {
                    [weak.tableView.mj_footer endRefreshingWithNoMoreData];
                }
            }
            
        } fail:^(NSDictionary *dic) {
            [weak.tableView.mj_footer endRefreshing];
            [weak.tableView.mj_header endRefreshing];
        }];
    }
    else
    {
        [GetAlertListApi getAlertListWithDeviceMac:self.deviceMac page:self.page success:^(NSArray<AlertModel *> *list) {
            [weak.tableView.mj_footer endRefreshing];
            [weak.tableView.mj_header endRefreshing];
            if (weak.page == 1)
            {
                [weak.dataSource removeAllObjects];
                [weak.dataSource addObjectsFromArray:list];
                [weak.tableView reloadData];
            }
            else
            {
                if (list.count != 0)
                {
                    [weak.dataSource addObjectsFromArray:list];
                    [weak.tableView reloadData];
                }
                else
                {
                    [weak.tableView.mj_footer endRefreshingWithNoMoreData];
                }
            }
        } fail:^(NSDictionary *dic) {
            [weak.tableView.mj_footer endRefreshing];
            [weak.tableView.mj_header endRefreshing];
        }];
    }

}

#pragma mark - --------------------------UITableView delegate--------------------------

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UnlockingHistoryTableViewCell *cell = [UnlockingHistoryTableViewCell dequeueReusableWithTableView:tableView];
    if (self.type == 0)
    {
        [cell updateCellDataWithUnlockingModel:self.dataSource[indexPath.row]];
    }
    else
    {
        [cell updateCellDataWithAlertModel:self.dataSource[indexPath.row]];
    }
    
    
    if (self.dataSource.count == 1)
    {
        cell.iconImageView.image = [UIImage imageNamed:@"icon_cell4"];
    }
    else if (self.dataSource.count == 2)
    {
        if (indexPath.row == 0)
        {
            cell.iconImageView.image = [UIImage imageNamed:@"icon_cell1"];
        }
        else
        {
            cell.iconImageView.image = [UIImage imageNamed:@"icon_cell2"];
        }
    }
    else if (self.dataSource.count == 3)
    {
        if (indexPath.row == 0)
        {
            cell.iconImageView.image = [UIImage imageNamed:@"icon_cell1"];
        }
        else if (indexPath.row == 1)
        {
            cell.iconImageView.image = [UIImage imageNamed:@"icon_cell3"];
        }
        else
        {
            cell.iconImageView.image = [UIImage imageNamed:@"icon_cell6"];
        }
    }
    else
    {
        if (indexPath.row == 0)
        {
            cell.iconImageView.image = [UIImage imageNamed:@"icon_cell1"];
        }
        else if (indexPath.row == 1)
        {
            cell.iconImageView.image = [UIImage imageNamed:@"icon_cell3"];
        }
        else if (indexPath.row == self.dataSource.count - 1)
        {
            cell.iconImageView.image = [UIImage imageNamed:@"icon_cell6"];
        }
        else
        {
            cell.iconImageView.image = [UIImage imageNamed:@"icon_cell5"];
        }

    }
//    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    return cell;
}
#pragma mark - --------------------------UITableView delegate--------------------------
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return CGFLOAT_MIN;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

#pragma mark - --------------------------懒加载--------------------------
- (UITableView *)tableView{
    
    if (!_tableView) {
        
        __weak UIView *superView = self.view;
        __weak typeof(self) weak = self;
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        [superView addSubview:_tableView];
        _tableView.separatorStyle = UITableViewCellSelectionStyleNone;//隐藏tableView的分割线
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            weak.page = 1;
            [weak updateDataSource];
        }];
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            weak.page ++;
            [weak updateDataSource];
        }];
    }
    return _tableView;
}

- (UIView *)headView
{
    if(!_headView)
    {
        UIView *superView = self.view;
        _headView = [[UIView alloc]init];
        [superView addSubview:_headView];
        _headView.backgroundColor = [UIColor colorWithRed:34/255.0 green:24/255.0 blue:22/255.0 alpha:1];
    }
    return _headView;
}
- (UIButton *)doorButton
{
    if(!_doorButton)
    {
        UIView *superView = self.headView;
        _doorButton = [[UIButton alloc]init];
        [superView addSubview:_doorButton];
        [_doorButton setBackgroundImage:[UIImage imageNamed:@"icon_lock_off"] forState:UIControlStateNormal];
        [_doorButton setBackgroundImage:[UIImage imageNamed:@"icon_lock_on"] forState:UIControlStateSelected];
        [_doorButton addTarget:self action:@selector(didClickDoorButton) forControlEvents:UIControlEventTouchUpInside];
    }
    return _doorButton;
}
- (UISegmentedControl *)segmentedControl
{
    if(!_segmentedControl)
    {
        UIView *superView = self.view;
        _segmentedControl = [[UISegmentedControl alloc]initWithItems:@[@"开锁记录",@"报警记录"]];
        [superView addSubview:_segmentedControl];
        _segmentedControl.tintColor = [UIColor colorWithRed:216/255.0 green:184/255.0 blue:108/255.0 alpha:1];
        [_segmentedControl addTarget:self action:@selector(didClicksegmentedControlAction:) forControlEvents:UIControlEventValueChanged];
        _segmentedControl.selectedSegmentIndex = self.type;
    }
    return _segmentedControl;
}

- (NSMutableArray *)dataSource
{
    if(!_dataSource)
    {
        _dataSource = [[NSMutableArray alloc] initWithArray:@[]];
    }
    return _dataSource;
}



#pragma mark - --------------------------约束--------------------------
- (void)masLayoutSubview{
    
    __weak UIView *superView = self.view;
    __weak typeof(self) weak = self;
    superView.backgroundColor = [UIColor whiteColor];
    
    [self.headView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_equalTo(superView);
        make.height.mas_equalTo(pxScaleHeight(460));
    }];
    
    [self.doorButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(_headView);
    }];
    
    [self.segmentedControl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_headView.mas_bottom).with.offset(pxScaleHeight(35));
        make.centerX.mas_equalTo(superView.mas_centerX);
        make.width.mas_equalTo(pxScaleWidth(750));
        make.height.mas_equalTo(pxScaleHeight(100));
    }];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_segmentedControl.mas_bottom).with.offset(pxScaleHeight(35));
        make.bottom.left.right.mas_equalTo(superView);
    }];
}

#pragma mark - --------------------------导航栏--------------------------
- (void)setNavigationStyle
{
    [self setLeftButtonImage:[UIImage imageNamed:@"icon_back_nor"]];
    [self setRightButtonImage:[UIImage imageNamed:@"title_icon_set_nor"]];
    [self setNavigationTitle:@"入户门锁" titleColor:nil];
    [self hideNavigationBottomLine];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
